<?php

namespace app\uapi\controller;

use app\admin\model\KnscyUserPeople;
use app\common\controller\ApiController;
use app\common\service\UserService;
use app\common\service\WeginService;
use think\facade\Db;

class People extends  ApiController
{
    public static $needLoginAction = [
        'getPeopleList',
        'getPeople',
        'delPeople',
        'addPeople',
    ];
    /**
     * 获取当前用户的出行人列表
     * @return void
     */
    public function getPeopleList()
    {
        $ids = $this->request->post('ids');
        $user_id = UserService::getUserIdByOpenid();

        $list = KnscyUserPeople::where('status', 1)
            ->where('user_id', $user_id)
            ->when( !empty($ids), function ($query) use ($ids) {
                $query->whereIn('id', $ids);
            })
            ->order(Db::raw('sort=0,sort asc,id desc'))
            ->field('id,first_name,name,mobile,identity,identity_type')
            ->select()->each(function ($item) use (&$pages) {
                $item['name'] = $item['first_name'] . $item['name'];
            });
        $this->success('success', $list);

    }
    public function getPeople()
    {
        $id = $this->request->post('id');
        $user_id = UserService::getUserIdByOpenid();
        $detail = KnscyUserPeople::where('status', 1)
            ->field('id,first_name,name,mobile,identity,identity_type')
            ->where('user_id', $user_id)
            ->where('id', $id)->find();
        $this->success('success', $detail);
    }
    public function delPeople()
    {
        $id = $this->request->post('id');
        $user_id = UserService::getUserIdByOpenid();
        $detail = KnscyUserPeople::where('status', 1)
            ->where('user_id', $user_id)
            ->where('id', $id)
            ->find();
        if (!empty($detail)) {
            $detail->delete();
        }
        $this->success('success');
    }

    /**
     * 新增出行人
     * @return void
     */
    public function addPeople()
    {
        $post = $this->request->post();
        $rules = [
            'name|名称' => 'require|max:25',
            'first_name|姓氏'=> 'require|max:20',
            'mobile|手机号'=> 'require|mobile',
        ];
        $this->validate($post, $rules);

        try{

            $post['uniacid'] = WeginService::getUniacid();
            $post['user_id'] = UserService::getUserIdByOpenid() ;
            if(isset($post['id'])){
                $model = KnscyUserPeople::find($post['id']);
                $save = $model->save($post);
            }else{
                $model = new KnscyUserPeople();
                $save = $model->save($post);
            }


        }catch (\Exception $e){
            $this->error($e->getMessage());
        }

        if($save){
            $this->success('success', $save);
        }else{
            $this->error('error');
        }
    }
}